<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <link type="text/css" rel="stylesheet" href="css/message.css">
</head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    var messageuserid = localStorage.getItem('messageuserid');
    var messageid = localStorage.getItem('messageid');
    var content = localStorage.getItem('content');
    var isself = localStorage.getItem('isself');

    console.log(isself)
    if (isself=="true"){
        $(document).ready(function() {
            var body = $('#button');
            //创建一个删除按钮
            var deletebutton = document.createElement('button');
            deletebutton.textContent = "删除";
            deletebutton.className = "styled-button";
            deletebutton.onclick = function () {
                $.ajax({
                    url: '/message/delete',
                    type: 'PUT',
                    data: {
                        id:messageid
                    },
                    success: function(response) {
                        alert("删除成功!")
                        localStorage.removeItem('messageid')
                        localStorage.removeItem('content')
                        localStorage.removeItem('messageuserid')
                        localStorage.removeItem('isself')
                        window.location.href = 'user_index.html';
                    },
                    error: function(xhr, status, error) {
                        console.error('发送数据失败:', error);
                    }
                })
            }


            //创建一个修改按钮
            var updatebutton = document.createElement('button');
            updatebutton.textContent = "修改";
            updatebutton.className = "styled-button";
            updatebutton.style.marginRight= "5px";
            updatebutton.onclick = function () {
                $.ajax({
                    url: '/message/delete',
                    type: 'PUT',
                    data: {
                        id:messageid
                    },
                    success: function(response) {
                        localStorage.removeItem('messageid')
                        localStorage.removeItem('content')
                        localStorage.removeItem('messageuserid')
                        localStorage.removeItem('isself')
                        window.location.href = 'addmessage.html';
                    },
                    error: function(xhr, status, error) {
                        console.error('发送数据失败:', error);
                    }
                })
            }
            body.append(updatebutton);
            body.append(deletebutton)

        });
    }

    var contentInput = $('#content');
    contentInput.empty();
    contentInput.text(content);

    // 获取用户名（异步）
    $.ajax({
        url: '/user/getUserById',
        type: 'POST',
        data: {
            id: messageuserid
        },
        success: function (data) {
            var user = data.data;
            var username = $('#username'); // 确保这个元素存在于DOM中
            console.log(user.username);
            username.text("--"+user.username)

            // 获取信息回复（异步）
            $.ajax({
                url: '/speak/getAllSpeaks',
                type: 'POST',
                data: {
                    messageid: messageid
                },
                success: function (data) {
                    var speaks = data.data;
                    var table = $('#table');

                    // 清空表格
                    table.empty();

                    // 遍历speaks数组并创建表格行
                    speaks.forEach(function(speak) {
                        var tr = $('<tr></tr>');
                        tr.append($('<td></td>').text(speak.talk));

                        // 获取每个speak的用户名（异步）
                        $.ajax({
                            url: '/user/getUserById',
                            type: 'POST',
                            data: {
                                id: speak.userid
                            },
                            success: function (userData) {
                                var one = userData.data;
                                tr.append($('<td style="text-align: right"></td>').text("--"+one.username));
                                table.append(tr); // 在获取用户名后添加行到表格
                            },
                            error: function() {
                                // 处理获取用户名失败的情况，例如添加一个占位符
                                tr.append($('<td></td>').text('Unknown User'));
                                table.append(tr);
                            }
                        });
                    });
                },
                error: function() {
                    // 处理获取speaks数据失败的情况
                    console.error('Failed to load speaks for message ID:', messageid);
                }
            });
        },
        error: function() {
            // 处理获取用户数据失败的情况
            console.error('Failed to load user for ID:', messageuserid);
        }
    });
</script>
<script>
    $(document).ready(function() {
        $('#speakForm').on('submit', function(event) {
            // 阻止表单的默认提交行为
            event.preventDefault();

            // 获取表单数据
            var talk = $('#talk').val()

            // 发送AJAX请求
            $.ajax({
                url: '/speak/insert',
                type: 'POST',
                data: {
                    talk:talk,
                    messageid:messageid
                },
                success: function(response) {
                    // 处理成功响应
                    console.log('数据已成功发送:', response);
                    // 这里可以添加额外的逻辑，比如显示成功消息、清空输入框等
                    $('#speakContent').val(''); // 清空输入框
                    window.location.href = window.location.href;

                },
                error: function(xhr, status, error) {
                    // 处理错误响应
                    console.error('发送数据失败:', error);
                    // 这里可以添加额外的逻辑，比如显示错误消息等
                }
            });
        });
    });
    if (isself=="true"){
        document.addEventListener('DOMContentLoaded', function () {
            // 选择按钮元素
            var returnButton = document.getElementById('returnButton');

            // 为按钮添加点击事件监听器
            returnButton.addEventListener('click', function () {
                // 跳转到 index.html
                localStorage.removeItem('messageid')
                localStorage.removeItem('content')
                localStorage.removeItem('messageuserid')
                localStorage.removeItem('isself')
                window.location.href = 'user_index.html';
            });

            // 选择按钮元素
            var updateButton = document.getElementById('update');

            // 为按钮添加点击事件监听器
            updateButton.addEventListener('click', function () {
                // 跳转到 index.html
                localStorage.removeItem('messageid')
                localStorage.removeItem('content')
                localStorage.removeItem('messageuserid')
                localStorage.removeItem('isself')
                window.location.href = 'user_index.html';
            });

            // 选择按钮元素
            var deleteButton = $('#deletebutton')
            console.log(deleteButton)

            // 为按钮添加点击事件监听器
            deleteButton.addEventListener('click', function () {
                alert("确定删除吗？")
                // 跳转到 index.html
                $.ajax({
                    url: '/message/delete',
                    type: 'POST',
                    data: {
                        id:messageid
                    },
                    success: function(response) {
                        alert("删除成功!")
                        localStorage.removeItem('messageid')
                        localStorage.removeItem('content')
                        localStorage.removeItem('messageuserid')
                        localStorage.removeItem('isself')
                        window.location.href = 'user_index.html';
                    },
                    error: function(xhr, status, error) {
                        console.error('发送数据失败:', error);
                    }
                })

            });
        });
    }else {
        document.addEventListener('DOMContentLoaded', function () {
            // 选择按钮元素
            var returnButton = document.getElementById('returnButton');

            // 为按钮添加点击事件监听器
            returnButton.addEventListener('click', function () {
                // 跳转到 index.html
                localStorage.removeItem('messageid')
                localStorage.removeItem('content')
                localStorage.removeItem('messageuserid')

                window.location.href = 'index.html';
            });
        });
    }
</script>

<body>
<div style="text-align: right" id="button">
    <button class="styled-button" id="returnButton">返回</button>
</div>
<div class="container">
    <div style="max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f9f9f9; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
        <p style="font-size: 16px; line-height: 1.5; color: #333; margin-bottom: 10px;" id="content">测试</p>
        <p style="font-size: 14px; line-height: 1.5; color: #666; text-align: right; margin-top: 0;" id="username">--测试</p>
    </div>
    <table id="table">
        <tr>
            <td>测试</td>
            <td>--测试</td>
        </tr>
    </table>
    <form class="styled-form" action="" id="speakForm">
        <input type="text" placeholder="请输入内容" id="talk">
        <button type="submit">发送</button>
    </form>
</div>
</body>
</html>